// 2013-8-3上午11:46:47  net.betou.web.PermistionDirective.java

package net.betou.web;

import static net.betou.trade.web.AdminContextInterceptor.PERMISSION_MODEL;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import net.betou.web.freemaker.DirectiveUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateScalarModel;
import freemarker.template.TemplateSequenceModel;

/**
 * 
 * @author 叶装装
 */
public class PermistionDirective implements TemplateDirectiveModel{
	/**
	 * 此url必须和perm中url一致。
	 */
	public static final String PARAM_URL = "url";

	/**
	 * 这里不考虑是否只读管理员
	 */
	@SuppressWarnings( "unchecked" )
	public void execute( Environment env, Map params, TemplateModel [ ] loopVars, TemplateDirectiveBody body ) throws TemplateException, IOException {
		String url = DirectiveUtils.getString( PARAM_URL, params );
		boolean pass = false;
		if( StringUtils.isNotBlank( url )){
			TemplateSequenceModel perms = getPerms( env );
			String perm;
			for ( int i = 0, len = perms.size( ); i < len; i++ ){
				perm = ( ( TemplateScalarModel ) perms.get( i ) ).getAsString( );
				if( url.startsWith( perm ) ){
					pass = true;
					break;
				}
			}
		}

		if( pass ){
			body.render( env.getOut( ) );
		}
	}

	private TemplateSequenceModel getPerms( Environment env ) throws TemplateModelException {
		TemplateModel model = env.getDataModel( ).get( PERMISSION_MODEL );
		if( model == null ){
			return null;
		}
		if( model instanceof TemplateSequenceModel ){
			return ( TemplateSequenceModel ) model;
		}else{
			throw new TemplateModelException( "'perms' in data model not a TemplateSequenceModel" );
		}

	}
	
	public static void main( String [ ] args ) {
		
		String x = "/system";
		String y = "/systemadmin/";
		
		System.out.println( y.startsWith( x ));
		
	}

}
